//
//  MVVM-C.m
//  DesignPattern
//
//  Created by jun on 2021/4/16.
//

#import "MVVM-C.h"
#import "MVVM-V.h"
#import "MVVM_VM.h"
#import <ReactiveObjC/RACSignal.h>
#import <RACSignal+Operations.h>

@interface MVVM_C ()

@property MVVM_VM *vm;
@property MVVM_V *view;

@end

@implementation MVVM_C

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    __block int count = 0;
    MVVM_V *view = [[MVVM_V alloc]initWithFrame:self.view.frame];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    __weak typeof(view) wView = view;
    view.touchBlock = ^{
        count++;
        __strong typeof(wView) sView = wView;
        sView.backgroundColor = count%2?[UIColor greenColor]:[UIColor redColor];
    };
    self.view = view;
    
    //V=》VM=〉V
    self.vm = [MVVM_VM new];
    [self.vm getUserData:^(BOOL success, NSDictionary * _Nonnull dic, NSString * _Nonnull msg, NSError * _Nonnull error) {
        __strong typeof(wView) sView = wView;
        [sView reloadView:[self getColor:dic[@"data"]]];
    }];
    view.vm = self.vm;
    [self bind];
}

-(UIColor *)getColor:(NSDictionary *)dic{
    if (dic) {
        if (dic[@"title"]) {
            return [UIColor greenColor];
        }else if (dic[@"desc"]){
            return [UIColor blueColor];
        }else{
            return [UIColor redColor];
        }
    }else{
        return [UIColor whiteColor];
    }
}
- (void)bind {
    //RAC 2 订阅消息
    [self.vm.updateDataCommand.executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {
        NSLog(@"%@",x);
        NSLog(@"subscribeNext");
        if (x) {
            self.view.backgroundColor = [UIColor grayColor];
        }else{
            self.view.backgroundColor = [UIColor yellowColor];
        }
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
